home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / nevow / testutil.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-03-23  |  24KB  |  583 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import os
  5. import sys
  6. import signal
  7.  
  8. try:
  9.     from popen2 import Popen3
  10. except ImportError:
  11.     Popen3 = None
  12.  
  13. from zope.interface import implements
  14.  
  15. try:
  16.     import subunit
  17. except ImportError:
  18.     subunit = None
  19.  
  20. from twisted.trial.unittest import TestCase as TrialTestCase
  21. from twisted.python.components import Componentized
  22. from twisted.internet import defer
  23. from twisted.web import http
  24. from twisted.protocols.basic import LineReceiver
  25. from formless import iformless
  26. from nevow import inevow, context, athena, loaders, tags, appserver
  27. from nevow.jsutil import findJavascriptInterpreter, generateTestScript
  28.  
  29. class FakeChannel:
  30.     
  31.     def __init__(self, site):
  32.         self.site = site
  33.  
  34.  
  35.  
  36. class FakeSite:
  37.     pass
  38.  
  39.  
  40. class FakeSession(Componentized):
  41.     implements(inevow.ISession)
  42.     
  43.     def __init__(self, avatar):
  44.         Componentized.__init__(self)
  45.         self.avatar = avatar
  46.         self.uid = 12345
  47.  
  48.     
  49.     def getLoggedInRoot(self):
  50.         return self.avatar
  51.  
  52.  
  53. fs = FakeSession(None)
  54.  
  55. class FakeRequest(Componentized):
  56.     '''
  57.     Implementation of L{inevow.IRequest} which is convenient to use in unit
  58.     tests.
  59.  
  60.     @ivar lastModified: The value passed to L{setLastModified} or C{None} if
  61.         that method has not been called.
  62.  
  63.     @type accumulator: C{str}
  64.     @ivar accumulator: The bytes written to the response body.
  65.  
  66.     @type deferred: L{Deferred}
  67.     @ivar deferred: The deferred which represents rendering of the response
  68.         to this request.  This is basically an implementation detail of
  69.         L{NevowRequest}.  Application code should probably never use this.
  70.  
  71.     @ivar _appRootURL: C{None} or the object passed to L{rememberRootURL}.
  72.     '''
  73.     implements(inevow.IRequest)
  74.     fields = None
  75.     failure = None
  76.     context = None
  77.     redirected_to = None
  78.     lastModified = None
  79.     content = ''
  80.     method = 'GET'
  81.     code = http.OK
  82.     deferred = None
  83.     accumulator = ''
  84.     _appRootURL = None
  85.     
  86.     def __init__(self, headers = None, args = None, avatar = None, uri = '/', currentSegments = None, cookies = None, user = '', password = '', isSecure = False):
  87.         '''Create a FakeRequest instance.
  88.  
  89.         headers:
  90.             dict of headers
  91.         args:
  92.             dict of args
  93.         avatar:
  94.             avatar to pass to the FakeSession instance
  95.         uri:
  96.             request URI
  97.         currentSegments:
  98.             list of segments that have "already been located"
  99.         cookies:
  100.             dict of cookies
  101.         user:
  102.             username (like in http auth)
  103.         password:
  104.             password (like in http auth)
  105.         isSecure:
  106.             whether this request represents an HTTPS url
  107.         '''
  108.         Componentized.__init__(self)
  109.         self.uri = uri
  110.         self.prepath = []
  111.         postpath = uri.split('?')[0]
  112.         if not postpath.startswith('/'):
  113.             raise AssertionError
  114.         self.postpath = postpath[1:].split('/')
  115.         self.headers = { }
  116.         if headers:
  117.             for k, v in headers.iteritems():
  118.                 self.setHeader(k, v)
  119.             
  120.         
  121.         if not args:
  122.             pass
  123.         self.args = { }
  124.         self.sess = FakeSession(avatar)
  125.         self.site = FakeSite()
  126.         self.received_headers = { }
  127.         if cookies is not None:
  128.             self.cookies = cookies
  129.         else:
  130.             self.cookies = { }
  131.         self.user = user
  132.         self.password = password
  133.         self.secure = isSecure
  134.         self.deferred = defer.Deferred()
  135.  
  136.     
  137.     def URLPath(self):
  138.         url = url
  139.         import nevow
  140.         return url.URL.fromString('')
  141.  
  142.     
  143.     def getSession(self):
  144.         return self.sess
  145.  
  146.     
  147.     def registerProducer(self, producer, streaming):
  148.         '''
  149.         Synchronously cause the given producer to produce all of its data.
  150.  
  151.         This will not work with push producers.  Do not use it with them.
  152.         '''
  153.         keepGoing = [
  154.             None]
  155.         self.unregisterProducer = keepGoing.pop
  156.         while keepGoing:
  157.             producer.resumeProducing()
  158.         del self.unregisterProducer
  159.  
  160.     
  161.     def v():
  162.         
  163.         def get(self):
  164.             return self.accumulator
  165.  
  166.         return (get,)
  167.  
  168.     v = property(*v())
  169.     
  170.     def write(self, bytes):
  171.         '''
  172.         Accumulate the given bytes as part of the response body.
  173.  
  174.         @type bytes: C{str}
  175.         '''
  176.         self.accumulator += bytes
  177.  
  178.     finished = False
  179.     
  180.     def finishRequest(self, success):
  181.         self.finished = True
  182.  
  183.     
  184.     def finish(self):
  185.         self.deferred.callback('')
  186.  
  187.     
  188.     def getHeader(self, key):
  189.         return self.headers.get(key.lower())
  190.  
  191.     
  192.     def setHeader(self, key, val):
  193.         self.headers[key.lower()] = val
  194.  
  195.     
  196.     def redirect(self, url):
  197.         self.redirected_to = url
  198.  
  199.     
  200.     def processingFailed(self, f):
  201.         self.failure = f
  202.  
  203.     
  204.     def setResponseCode(self, code):
  205.         self.code = code
  206.  
  207.     
  208.     def setLastModified(self, when):
  209.         self.lastModified = when
  210.  
  211.     
  212.     def prePathURL(self):
  213.         '''
  214.         The absolute URL up until the last handled segment of this request.
  215.  
  216.         @rtype: C{str}.
  217.         '''
  218.         if not self.getHeader('host'):
  219.             pass
  220.         return 'http://%s/%s' % ('localhost', '/'.join(self.prepath))
  221.  
  222.     
  223.     def getClientIP(self):
  224.         return '127.0.0.1'
  225.  
  226.     
  227.     def addCookie(self, k, v, expires = None, domain = None, path = None, max_age = None, comment = None, secure = None):
  228.         '''
  229.         Set a cookie for use in subsequent requests.
  230.         '''
  231.         self.cookies[k] = v
  232.  
  233.     
  234.     def getCookie(self, k):
  235.         '''
  236.         Fetch a cookie previously set.
  237.         '''
  238.         return self.cookies.get(k)
  239.  
  240.     
  241.     def getUser(self):
  242.         '''
  243.         Returns the HTTP auth username.
  244.         '''
  245.         return self.user
  246.  
  247.     
  248.     def getPassword(self):
  249.         '''
  250.         Returns the HTTP auth password.
  251.         '''
  252.         return self.password
  253.  
  254.     
  255.     def getRootURL(self):
  256.         '''
  257.         Return the previously remembered URL.
  258.         '''
  259.         return self._appRootURL
  260.  
  261.     
  262.     def rememberRootURL(self, url = None):
  263.         '''
  264.         For compatibility with appserver.NevowRequest.
  265.         '''
  266.         if url is None:
  267.             raise NotImplementedError('Default URL remembering logic is not implemented.')
  268.         url is None
  269.         self._appRootURL = url
  270.  
  271.     
  272.     def isSecure(self):
  273.         '''
  274.         Returns whether this is an HTTPS request or not.
  275.         '''
  276.         return self.secure
  277.  
  278.  
  279.  
  280. class TestCase(TrialTestCase):
  281.     hasBools = sys.version_info >= (2, 3)
  282.     _assertions = 0
  283.     
  284.     def failUnlessSubstring(self, containee, container, msg = None):
  285.         self._assertions += 1
  286.         if container.find(containee) == -1:
  287.             if not msg:
  288.                 pass
  289.             self.fail('%r not in %r' % (containee, container))
  290.         
  291.  
  292.     
  293.     def failIfSubstring(self, containee, container, msg = None):
  294.         self._assertions += 1
  295.         if container.find(containee) != -1:
  296.             if not msg:
  297.                 pass
  298.             self.fail('%r in %r' % (containee, container))
  299.         
  300.  
  301.     assertSubstring = failUnlessSubstring
  302.     assertNotSubstring = failIfSubstring
  303.     
  304.     def assertNotIdentical(self, first, second, msg = None):
  305.         self._assertions += 1
  306.         if first is second:
  307.             if not msg:
  308.                 pass
  309.             self.fail('%r is %r' % (first, second))
  310.         
  311.  
  312.     
  313.     def failIfIn(self, containee, container, msg = None):
  314.         self._assertions += 1
  315.         if containee in container:
  316.             if not msg:
  317.                 pass
  318.             self.fail('%r in %r' % (containee, container))
  319.         
  320.  
  321.     
  322.     def assertApproximates(self, first, second, tolerance, msg = None):
  323.         self._assertions += 1
  324.         if abs(first - second) > tolerance:
  325.             if not msg:
  326.                 pass
  327.             self.fail('%s ~== %s' % (first, second))
  328.         
  329.  
  330.  
  331. if not hasattr(TrialTestCase, 'mktemp'):
  332.     
  333.     def mktemp(self):
  334.         import tempfile as tempfile
  335.         return tempfile.mktemp()
  336.  
  337.     TestCase.mktemp = mktemp
  338.  
  339.  
  340. class AccumulatingFakeRequest(FakeRequest):
  341.     '''
  342.     I am a fake IRequest that is also a stub implementation of
  343.     IFormDefaults.
  344.  
  345.     This class is named I{accumulating} for historical reasons only.  You
  346.     probably want to ignore this and use L{FakeRequest} instead.
  347.     '''
  348.     implements(iformless.IFormDefaults)
  349.     
  350.     def __init__(self, *a, **kw):
  351.         FakeRequest.__init__(self, *a, **kw)
  352.         self.d = defer.Deferred()
  353.  
  354.     
  355.     def getDefault(self, key, context):
  356.         return ''
  357.  
  358.     
  359.     def remember(self, object, interface):
  360.         pass
  361.  
  362.  
  363.  
  364. class FragmentWrapper(athena.LivePage):
  365.     '''
  366.     I wrap myself around an Athena fragment, providing a minimal amount of html
  367.     scaffolding in addition to an L{athena.LivePage}.
  368.     '''
  369.     docFactory = loaders.stan(tags.html[tags.body[tags.directive('fragment')]])
  370.     
  371.     def __init__(self, f):
  372.         super(FragmentWrapper, self).__init__()
  373.         self.f = f
  374.  
  375.     
  376.     def render_fragment(self, ctx, data):
  377.         self.f.setFragmentParent(self)
  378.         return self.f
  379.  
  380.  
  381.  
  382. def renderLivePage(res, topLevelContext = context.WebContext, reqFactory = FakeRequest):
  383.     '''
  384.     Render the given LivePage resource, performing LivePage-specific cleanup.
  385.     Return a Deferred which fires when it has rendered.
  386.     '''
  387.     D = renderPage(res, topLevelContext, reqFactory)
  388.     return (D.addCallback,)((lambda x: (res._messageDeliverer.close(), x)[1]))
  389.  
  390.  
  391. def renderPage(res, topLevelContext = context.WebContext, reqFactory = FakeRequest):
  392.     '''
  393.     Render the given resource.  Return a Deferred which fires when it has
  394.     rendered.
  395.     '''
  396.     req = reqFactory()
  397.     ctx = topLevelContext(tag = res)
  398.     ctx.remember(req, inevow.IRequest)
  399.     render = appserver.NevowRequest(None, True).gotPageContext
  400.     result = render(ctx)
  401.     (result.addCallback,)((lambda x: req.accumulator))
  402.     return result
  403.  
  404.  
  405. class NotSupported(Exception):
  406.     '''
  407.     Raised by L{JavaScriptTestCase} if the installation lacks a certain
  408.     required feature.
  409.     '''
  410.     pass
  411.  
  412.  
  413. class TestProtocolLineReceiverServer(LineReceiver):
  414.     '''
  415.     Subunit protocol which is also a Twisted LineReceiver so that it
  416.     includes line buffering logic.
  417.     '''
  418.     delimiter = '\n'
  419.     
  420.     def __init__(self, proto):
  421.         self.proto = proto
  422.  
  423.     
  424.     def lineReceived(self, line):
  425.         """
  426.         Forward the line on to the subunit protocol's lineReceived method,
  427.         which expects it to be newline terminated.
  428.         """
  429.         self.proto.lineReceived(line + '\n')
  430.  
  431.  
  432.  
  433. class JavaScriptTestCase(TrialTestCase):
  434.     
  435.     def __init__(self, methodName = 'runTest'):
  436.         TrialTestCase.__init__(self, methodName)
  437.         self.testMethod = getattr(self, methodName)
  438.  
  439.     
  440.     def findJavascriptInterpreter(self):
  441.         '''
  442.         @see L{nevow.jsutil.findJavascriptInterpreter}
  443.         '''
  444.         return findJavascriptInterpreter()
  445.  
  446.     
  447.     def checkDependencies(self):
  448.         '''
  449.         Check that all the dependencies of the test are satisfied.
  450.  
  451.         @raise NotSupported: If any one of the dependencies is not satisfied.
  452.         '''
  453.         js = self.findJavascriptInterpreter()
  454.         if js is None:
  455.             raise NotSupported('Could not find JavaScript interpreter')
  456.         js is None
  457.         if subunit is None:
  458.             raise NotSupported("Could not import 'subunit'")
  459.         subunit is None
  460.         if Popen3 is None:
  461.             raise NotSupported("Could not import 'popen2.Popen3'")
  462.         Popen3 is None
  463.         for name in [
  464.             'WEXITSTATUS',
  465.             'WIFSIGNALED',
  466.             'WTERMSIG']:
  467.             if getattr(os, name, None) is None:
  468.                 raise NotSupported('os.%s unavailable' % (name,))
  469.             getattr(os, name, None) is None
  470.         
  471.  
  472.     
  473.     def _writeToTemp(self, contents):
  474.         fname = self.mktemp()
  475.         fd = file(fname, 'w')
  476.         
  477.         try:
  478.             fd.write(contents)
  479.         finally:
  480.             fd.close()
  481.  
  482.         return fname
  483.  
  484.     
  485.     def createSource(self, testModule):
  486.         '''
  487.         Return a string of JavaScript source code which, when executed, will
  488.         run the JavaScript unit tests defined in the given module.
  489.  
  490.         @type testModule: C{str}
  491.         @param testModule: The JavaScript module name which contains the
  492.         tests to run.
  493.  
  494.         @rtype: C{str}
  495.         '''
  496.         js = '\n// import Divmod.UnitTest\n// import %(module)s\n\nDivmod.UnitTest.runRemote(Divmod.UnitTest.loadFromModule(%(module)s));\n' % {
  497.             'module': testModule }
  498.         return js
  499.  
  500.     
  501.     def makeScript(self, testModule):
  502.         '''
  503.         Write JavaScript source for executing the JavaScript unit tests in
  504.         the given JavaScript module to a file and return the name of that
  505.         file.
  506.  
  507.         @type testModule: C{str}
  508.         @param testModule: The JavaScript module name which contains the
  509.         tests to run.
  510.  
  511.         @rtype: C{str}
  512.         '''
  513.         jsfile = self._writeToTemp(self.createSource(testModule))
  514.         scriptFile = self._writeToTemp(generateTestScript(jsfile))
  515.         return scriptFile
  516.  
  517.     
  518.     def _runWithSigchild(self, f, *a, **kw):
  519.         '''
  520.         Run the given function with an alternative SIGCHLD handler.
  521.         '''
  522.         oldHandler = signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  523.         
  524.         try:
  525.             return f(*a, **kw)
  526.         finally:
  527.             signal.signal(signal.SIGCHLD, oldHandler)
  528.  
  529.  
  530.     
  531.     def run(self, result):
  532.         
  533.         try:
  534.             self.checkDependencies()
  535.         except NotSupported:
  536.             e = None
  537.             result.startTest(self)
  538.             result.addSkip(self, str(e))
  539.             result.stopTest(self)
  540.             return None
  541.  
  542.         js = self.findJavascriptInterpreter()
  543.         script = self.makeScript(self.testMethod())
  544.         server = subunit.TestProtocolServer(result)
  545.         protocol = TestProtocolLineReceiverServer(server)
  546.         
  547.         def run():
  548.             child = Popen3([
  549.                 js,
  550.                 script])
  551.             while True:
  552.                 bytes = child.fromchild.read(4096)
  553.                 if bytes:
  554.                     protocol.dataReceived(bytes)
  555.                     continue
  556.                 break
  557.             exitCode = child.wait()
  558.             if os.WIFSIGNALED(exitCode):
  559.                 result.addError(self, (Exception, 'JavaScript interpreter exited due to signal %d' % (os.WTERMSIG(exitCode),), None))
  560.             else:
  561.                 exitStatus = os.WEXITSTATUS(exitCode)
  562.                 if exitStatus:
  563.                     result.addError(self, (Exception, 'JavaScript interpreter had error exit: %d' % (exitStatus,), None))
  564.                 
  565.  
  566.         self._runWithSigchild(run)
  567.  
  568.  
  569.  
  570. def setJavascriptInterpreterOrSkip(testCase):
  571.     """
  572.     If we're unable to find a javascript interpreter (currently we only look
  573.     for smjs or js) then set the C{skip} attribute on C{testCase}. Otherwise
  574.     assign the path to the interpreter executable to
  575.     C{testCase.javascriptInterpreter}
  576.     """
  577.     script = findJavascriptInterpreter()
  578.     if script is None:
  579.         testCase.skip = 'No JavaScript interpreter available.'
  580.     else:
  581.         testCase.javascriptInterpreter = script
  582.  
  583.